package org.springblade.auth.granter;

import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.util.ObjectUtil;
import org.springblade.auth.constant.AuthConstant;
import org.springblade.auth.service.BladeUserDetails;
import org.springblade.auth.utils.TokenUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.support.Kv;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.WebUtil;
import org.springblade.system.entity.User;
import org.springblade.system.entity.UserInfo;
import org.springblade.system.entity.UserOauth;
import org.springblade.system.feign.IUserClient;
import org.springblade.weixin.feign.IWeixinClient;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.Map;

public class WeixinMiniAppTokenGranter extends AbstractTokenGranter {

	private static final String GRANT_TYPE = "wxminiapp";

	private final IUserClient userClient;

	private final IWeixinClient weixinClient;

	protected WeixinMiniAppTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, IUserClient userClient, IWeixinClient weixinClient) {
		super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
		this.userClient = userClient;
		this.weixinClient = weixinClient;
	}

	@Override
	protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
		// 请求头租户信息
		HttpServletRequest request = WebUtil.getRequest();
		String tenantId = Func.toStr(request.getHeader(TokenUtil.TENANT_HEADER_KEY), TokenUtil.DEFAULT_TENANT_ID);

		Map<String, String> parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());

		// 微信小程序临时登录code
		String code = parameters.get("code");

		WxMaJscode2SessionResult code2Session = weixinClient.getCode2Session(code);
		if (ObjectUtil.isNull(code2Session)){
			throw new InvalidGrantException("微信登录失败");
		}

		// 获取微信openid
		String openId = code2Session.getOpenid();

		// 组装数据
		UserOauth userOauth = new UserOauth();
		userOauth.setUuid(openId);
		userOauth.setUsername(openId);
		userOauth.setSource("wxminiapp");
		userOauth.setTenantId(tenantId);

		// 远程调用，获取认证信息
		R<UserInfo> result = userClient.userAuthInfo(userOauth);
		BladeUserDetails bladeUserDetails;
		if (result.isSuccess()) {
			User user = result.getData().getUser();
			Kv detail = result.getData().getDetail();
			if (user == null || user.getId() == null || user.getAccount() == null) {
				throw new InvalidGrantException("social grant failure, user is null");
			}
			bladeUserDetails = new BladeUserDetails(user.getId(),
				tenantId, result.getData().getOauthId(), user.getName(), user.getRealName(), user.getDeptId(), user.getPostId(), user.getRoleId(), Func.join(result.getData().getRoles()), Func.toStr(userOauth.getAvatar(), TokenUtil.DEFAULT_AVATAR),
				userOauth.getUsername(), AuthConstant.ENCRYPT + user.getPassword(), detail, true, true, true, true,
				AuthorityUtils.commaSeparatedStringToAuthorityList(Func.join(result.getData().getRoles())));
		} else {
			throw new InvalidGrantException("social grant failure, feign client return error");
		}

		// 组装认证数据，关闭密码校验
		Authentication userAuth = new UsernamePasswordAuthenticationToken(bladeUserDetails, null, bladeUserDetails.getAuthorities());
		((AbstractAuthenticationToken) userAuth).setDetails(parameters);
		OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);

		// 返回 OAuth2Authentication
		return new OAuth2Authentication(storedOAuth2Request, userAuth);
	}


}
